package com.berry.MedCheck.db;

import android.content.*;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import java.util.HashMap;

public class UserDBProvider extends ContentProvider {
	private static final String TAG = "LocationProvider";

	private static final String DATABASE_NAME = "locations.db";
	private static final int DATABASE_VERSION = 2;
	private static final String TABLE_NAME = "dataz";
	private static final String TABLE_MEASURE = "measure";

	private static HashMap<String, String> sProjectionMap;

	private static final int LOCATIONS = 1;
	private static final int LOCATION_ID = 2;

	private static final int MEASURE = 11;
	private static final int MEASURE_ID = 12;

	private static final UriMatcher sUriMatcher;

	/**
	 * This class helps open, create, and upgrade the database file.
	 */
	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
					+ UserDB.DBColumns._ID + " INTEGER PRIMARY KEY,"
					+ UserDB.DBColumns.USERNAME + " TEXT,"
					+ UserDB.DBColumns.CREATED_DATE + " INTEGER,"
					+ UserDB.DBColumns.SEX + " NUMERIC,"
					+ UserDB.DBColumns.AGE + " NUMERIC,"
					+ UserDB.DBColumns.HEIGHT + " NUMERIC,"
					+ UserDB.DBColumns.WEIGHT + " NUMERIC"

					+ ");");
			db.execSQL("CREATE TABLE " + TABLE_MEASURE + " ("
					+ UserDB.DBColumns._ID + " INTEGER PRIMARY KEY,"
					+ UserDB.DBColumns.USERID + " INTEGER,"
					+ UserDB.DBColumns.DATE + " INTEGER,"
					+ UserDB.DBColumns.SPO2 + " NUMERIC,"
					+ UserDB.DBColumns.PR + " NUMERIC,"
					+ UserDB.DBColumns.PI + " NUMERIC"
					+ ");");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS dataz");
			onCreate(db);
		}
	}

	private DatabaseHelper mOpenHelper;

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		String sTable = null;
		String orderBy =UserDB.DBColumns.DEFAULT_SORT_ORDER;
		if (sUriMatcher.match(uri) == LOCATIONS  || sUriMatcher.match(uri) == LOCATION_ID) {
			sTable = TABLE_NAME;
			if (TextUtils.isEmpty(sortOrder)) {
				orderBy = UserDB.DBColumns.DEFAULT_SORT_ORDER;
			} else {
				orderBy = sortOrder;
			}

		}  else if (sUriMatcher.match(uri) == MEASURE || sUriMatcher.match(uri) == MEASURE_ID) {
			sTable = TABLE_MEASURE;
			if (TextUtils.isEmpty(sortOrder)) {
				orderBy = UserDB.DBColumns.DEFAULT_MEAUSURE_SORT_ORDER;
			} else {
				orderBy = sortOrder;
			}
		}
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(sTable);

		switch (sUriMatcher.match(uri)) {
			case LOCATIONS:
				qb.setProjectionMap(sProjectionMap);
				break;

			case LOCATION_ID:
				qb.setProjectionMap(sProjectionMap);
				qb.appendWhere(UserDB.DBColumns._ID + "=" + uri.getPathSegments().get(1));
				break;
			case MEASURE:
				qb.setProjectionMap(sProjectionMap);
				break;

			case MEASURE_ID:
				qb.setProjectionMap(sProjectionMap);
				qb.appendWhere(UserDB.DBColumns._ID + "=" + uri.getPathSegments().get(1));
				break;
			default:
				throw new IllegalArgumentException("Unknown URI " + uri);
		}

		// Get the database and run the query
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

		// Tell the cursor what uri to watch, so it knows when its source data changes
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
			case LOCATIONS:
				return UserDB.DBColumns.CONTENT_TYPE;

			case LOCATION_ID:
				return UserDB.DBColumns.CONTENT_ITEM_TYPE;
			case MEASURE:
				return UserDB.DBColumns.CONTENT_TYPE;

			case MEASURE_ID:
				return UserDB.DBColumns.CONTENT_ITEM_TYPE;

			default:
				throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		// Validate the requested uri
		if (sUriMatcher.match(uri) == LOCATIONS) {

			ContentValues values;
			if (initialValues != null) {
				values = new ContentValues(initialValues);
			} else {
				values = new ContentValues();
			}
			Long now = System.currentTimeMillis();

			// Make sure that the fields are all set
			if (values.containsKey(UserDB.DBColumns.CREATED_DATE) == false) {
				values.put(UserDB.DBColumns.CREATED_DATE, now);
			}
			if (values.containsKey(UserDB.DBColumns.USERNAME) == false) {
				Resources r = Resources.getSystem();
				values.put(UserDB.DBColumns.USERNAME, r.getString(android.R.string.untitled));
			}
			if (values.containsKey(UserDB.DBColumns.SEX) == false) {
				values.put(UserDB.DBColumns.SEX, 0);
			}
			if (values.containsKey(UserDB.DBColumns.AGE) == false) {
				values.put(UserDB.DBColumns.AGE, 0);
			}
			if (values.containsKey(UserDB.DBColumns.HEIGHT) == false) {
				values.put(UserDB.DBColumns.HEIGHT, 0);
			}
			if (values.containsKey(UserDB.DBColumns.WEIGHT) == false) {
				values.put(UserDB.DBColumns.WEIGHT, 0);
			}
			SQLiteDatabase db = mOpenHelper.getWritableDatabase();
			long rowId = db.insert(TABLE_NAME, UserDB.DBColumns.USERNAME, values);
			if (rowId > 0) {
				Uri noteUri = ContentUris.withAppendedId(UserDB.DBColumns.CONTENT_URI, rowId);
				getContext().getContentResolver().notifyChange(noteUri, null);
				return noteUri;
			}
		}
		if (sUriMatcher.match(uri) == MEASURE) {
			ContentValues values;
			if (initialValues != null) {
				values = new ContentValues(initialValues);
			} else {
				values = new ContentValues();
			}

			Long now = (System.currentTimeMillis());

			SQLiteDatabase db = mOpenHelper.getWritableDatabase();
			long rowId = db.insert(TABLE_MEASURE, UserDB.DBColumns.DATE, values);
			if (rowId > 0) {
				Uri noteUri = ContentUris.withAppendedId(UserDB.DBColumns.MEASURE_URI, rowId);
				getContext().getContentResolver().notifyChange(noteUri, null);
				return noteUri;
			}
		}


		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		String sTable = null;
		if (sUriMatcher.match(uri) == LOCATIONS) {
			sTable = TABLE_NAME;
		} else if (sUriMatcher.match(uri) == MEASURE) {
			sTable = TABLE_MEASURE;
		}
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (sUriMatcher.match(uri)) {
			case LOCATIONS:
				count = db.delete(sTable, where, whereArgs);
				break;

			case LOCATION_ID:
				String noteId = uri.getPathSegments().get(1);
				count = db.delete(sTable, UserDB.DBColumns._ID + "=" + noteId
						+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
				break;
			case MEASURE:
				count = db.delete(sTable, where, whereArgs);
				break;

			case MEASURE_ID:
				String Id = uri.getPathSegments().get(1);
				count = db.delete(sTable, UserDB.DBColumns._ID + "=" + Id
						+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
				break;

			default:
				throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (sUriMatcher.match(uri)) {
			case LOCATIONS:
				count = db.update(TABLE_NAME, values, where, whereArgs);
				break;

			case LOCATION_ID:
				String noteId = uri.getPathSegments().get(1);
				count = db.update(TABLE_NAME, values, UserDB.DBColumns._ID + "=" + noteId
						+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
				break;

			case MEASURE:
				count = db.update(TABLE_MEASURE, values, where, whereArgs);
				break;

			case MEASURE_ID:
				String Id = uri.getPathSegments().get(1);
				count = db.update(TABLE_MEASURE, values, UserDB.DBColumns._ID + "=" + Id
						+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
				break;

			default:
				throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(UserDB.AUTHORITY, "dataz", LOCATIONS);
		sUriMatcher.addURI(UserDB.AUTHORITY, "dataz/#", LOCATION_ID);

		sUriMatcher.addURI(UserDB.AUTHORITY, "measure", MEASURE);
		sUriMatcher.addURI(UserDB.AUTHORITY, "measure/#", MEASURE_ID);


		sProjectionMap = new HashMap<String, String>();
		sProjectionMap.put(UserDB.DBColumns._ID, UserDB.DBColumns._ID);
		sProjectionMap.put(UserDB.DBColumns.USERNAME, UserDB.DBColumns.USERNAME);
		sProjectionMap.put(UserDB.DBColumns.CREATED_DATE, UserDB.DBColumns.CREATED_DATE);
		sProjectionMap.put(UserDB.DBColumns.SEX, UserDB.DBColumns.SEX);
		sProjectionMap.put(UserDB.DBColumns.AGE, UserDB.DBColumns.AGE);
		sProjectionMap.put(UserDB.DBColumns.HEIGHT, UserDB.DBColumns.HEIGHT);
		sProjectionMap.put(UserDB.DBColumns.WEIGHT, UserDB.DBColumns.WEIGHT);


		sProjectionMap.put(UserDB.DBColumns.USERID, UserDB.DBColumns.USERID);
		sProjectionMap.put(UserDB.DBColumns.DATE, UserDB.DBColumns.DATE);
		sProjectionMap.put(UserDB.DBColumns.SPO2, UserDB.DBColumns.SPO2);
		sProjectionMap.put(UserDB.DBColumns.PR, UserDB.DBColumns.PR);
		sProjectionMap.put(UserDB.DBColumns.PI, UserDB.DBColumns.PI);


	}

}